package com.example.gobang.api;

import com.example.gobang.model.User;
import com.example.gobang.model.UserMapper;
import com.example.gobang.my_package.MyMethod;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class UserAPI {
    @Resource
    private UserMapper userMapper;
    int au = 0;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest req) {
        User user = userMapper.selectByName(username);
        System.out.println("[login] username = " + username);
        if (user == null || !user.getPassword().equals(password)) {
            /*System.out.println("登陆失败！");*/
            return new User();
        }

        HttpSession httpSession = req.getSession(true);
        httpSession.setAttribute("user", user);

        return user;
    }

    @PostMapping("/verify")
    @ResponseBody
    public int verify(String phoneNumber) {
        User user = userMapper.selectByPhoneNumber(phoneNumber);
        if (MyMethod.countDigits(phoneNumber) != 11) {
            return 2; //号码格式错误
        } else if (user == null) {
            return 1; //可注册的号码
        } else {
            return 3; //已被注册号码
        }
    }

    @PostMapping("/register1")
    @ResponseBody
    public int register1(int authorize) {
        au = authorize;
        return 1;
    }

    @PostMapping("/register2")
    @ResponseBody
    public  int register2(String phoneNumber, int authorize_num, String password1, String password2) {
        if (au != authorize_num) {
            System.out.println(au);
            System.out.println(authorize_num);
            return 2; //授权码错误
        } else if (!password1.equals(password2)) {
            System.out.println(password1);
            System.out.println(password2);
            return 3; //两次密码不相同
        } else {
            User user = new User();
            user.setUsername(phoneNumber);
            user.setPassword(password1);
            user.setPhoneNumber(phoneNumber);
            userMapper.insert(user);
            return 1;
        }
    }

    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUerInfo(HttpServletRequest req) {
        HttpSession httpSession = req.getSession(false);
        User user = (User) httpSession.getAttribute(("user"));
        System.out.println(user.getUserId() + "," +user.getUsername() + "," +user.getPassword() +
                "," +user.getCoin() + "," +user.getPhoneNumber() + "," +user.getWinCount() +
                "," +user.getTotalCount());
        return user;
    }
}